<?php
namespace app\common\logic;

use think\Db;

//商户类
class Seller
{
    /**
     *添加商户
     * @param $data
     * @return array
     */
    public function addSeller($data)
    {
        $res = $this->checkSeller($data);
        if ($res['code'] == -1) {
            return $res;
        }
        $insertData = $res['data'];
        $insertData['oid'] = 1;
        $insertData['create_time'] = time();

        //判断用户是否存在
        $check = Db::name('seller')->field('id')->where(['mobile'=> $insertData['mobile']])->find();
        if ($check) {
            return output('-1', '商户绑定号码已经存在');
        }

        if(Db::name( 'seller')->insert($insertData)){
            return output(0, '添加成功');
        }else{
            return output(-1, '添加失败');
        }
    }



    /**
     *确认商户
     * @param array $data
     * @return array
     */
    public function checkSeller($data = [])
    {
        $sData['name'] = isset($data['name']) ? trim($data['name']) : '';
        if (empty($sData['name'])) {
            return output('-1', '请输入商户名称');
        }

        $sData['status'] = isset($data['status']) ? intval($data['status']) : '';
        if (empty($sData['status']) || !in_array($sData['status'], array_keys($this->getStatus()))) {
            return output('-1', '请选择正确的用户状态');
        }

        //绑定手机号
        $sData['mobile'] = isset($data['mobile']) ? $data['mobile'] : '';
        if (empty($sData['mobile']) || !Check::checkPhone($sData['mobile'])) {
            return output(-1, '请输入正确的绑定手机');
        }

        //设置单价
        $sData['per_price'] = isset($data['per_price']) ? $data['per_price'] : '';
        if (empty($sData['per_price']) || !is_numeric($sData['per_price']) || $sData['per_price'] <= 0) {
            return output(-1, '请设置正确的单价');
        }

        $sData['city'] = isset($data['city']) ? $data['city'] : '';
        $sData['province'] = isset($data['province']) ? $data['province'] : '';
        $isExist = Db::name('address')->field('id')->where(['addr_id' => $sData['province']])->find();
        if (empty($isExist)) {
            return output(-1, '请选择商户所在的省份');
        }
        $isExist = Db::name('address')->field('id')->where(['addr_id' => $sData['city']])->find();
        if (empty($isExist)) {
            return output(-1, '请选择商户所在的城市');
        }
        $sData['addr'] = isset($data['addr']) ? trim($data['addr']) : '';
        if (empty($sData['addr'])) {
            return output(-1, '请输入商户的详细地址');
        }

        //佣金比例
        $sData['brokerage'] = isset($data['brokerage']) ? intval($data['brokerage']) : '';
        if (empty($sData['brokerage']) || $sData['brokerage'] <= 0 || $sData['brokerage'] > 100) {
            return output(-1, '请输入正确的佣金比例1到100之间的整数');
        }

        $sData['shopstart'] = isset($data['shopstart']) ? $this->formatTime($data['shopstart']) : '';
        $sData['shopend'] = isset($data['shopend']) ? $this->formatTime($data['shopend']) : '';
        if ($sData['shopstart'] > 2400 || $sData['shopstart'] < 0) {
            return output(-1, '请选择正确的营业开始时间');
        }
        if ($sData['shopend'] > 2400 || $sData['shopend'] < 0) {
            return output(-1, '请选择正确的营业结束时间');
        }

        $sData['picture'] = isset($data['picture']) ? trim($data['picture']) : '';
        if (empty($sData['picture'])) {
            return output(-1, '请上传商户门店照');
        } else {
            $picS = explode(',', trim($sData['picture'], ','));
            $picture = '';
            foreach ($picS as $item) {
                $item = parse_url($item);
                if (isset($item['path']) && !empty($item['path'])) {
                    $item = $item['path'];
                } else {
                    return output('-1', '文件获取失败');
                }
                $picture .= $item.',';
            }
            $picture = trim($picture, ',');
            $sData['picture'] = $picture;
        }

        $sData['latitude'] = isset($data['latitude']) ? trim($data['latitude']) : '';
        if (empty($sData['latitude'])) {
            return output(-1, '请输入正确的商户所在纬度');
        }
        $sData['longitude'] = isset($data['longitude']) ? trim($data['longitude']) : '';
        if (empty($sData['longitude'])) {
            return output(-1, '请输入正确的商户所在经度');
        }
        $sData['phone'] = isset($data['phone']) ? trim($data['phone']) : '';
        $sData['averageprice'] = isset($data['averageprice']) ? trim($data['averageprice']) : '';
        $sData['contacts'] = isset($data['contacts']) ? trim($data['contacts']) : '';
        $sData['agency'] = isset($data['agency']) ? intval($data['agency']) : '0';
        $sData['salesman'] = isset($data['salesman']) ? intval($data['salesman']) : '0';
        return ['code' => 0, 'data' => $sData];
    }

    public function formatTime($time) {
        $time = explode(':', trim($time, ':'));
        if (isset($time[0]) && isset($time[1])) {
            $time = $time[0].$time[1];
        } else {
            $time = 0;
        }
        $time = intval($time);
        return $time;
    }

    public function parseTime($time) {
        $per = intval($time / 100);
        $last = intval($time %100);

        if (strlen($per) == 1) {
            $per = '0'.$per;
        }
        if (strlen($last) == 1) {
            $last = '0'.$last;
        }
        return $per.':'.$last;
    }
    /**
     *编辑商户
     *
     */
    public function editSeller($data)
    {
        $id = intval($data['id']);
        if (empty($id)) {
            return output(-1, '参数错误');
        }
        $updateData = $this->checkSeller($data);
        if ($updateData['code'] == '-1') {
            return $updateData;
        }
        $updateData = $updateData['data'];
        $updateData['oid'] = 1;
        $updateData['update_time'] = time();

        $isExist = Db::name('seller')
            ->field('id')
            ->where('id', '<>', $id)
            ->where(['mobile' => $updateData['mobile']])
            ->find();
        if ($isExist) {
            return output('-1', '该商户已经存在');
        }

        $res = Db::name('seller')->where(['id' => $id])->update($updateData);
        if ($res) {

            return output(0, '修改成功');
        } else {
            return output(-1, '修改失败');
        }
    }


    /**
     *获取代理商和地推
     *
     */
    public function getAgent()
    {
        $agentTmp = Db::name('agent')->where("is_use=1")->field('id,type,belong_agent,agent_name')->select();
        $agent = [];
        $sales = [];
        if ($agentTmp) {
            foreach($agentTmp as $val){
                if ($val['type'] == 1) {//代理商
                    $agent[$val['id']] = $val;
                } else {
                    $sales[$val['belong_agent']][] = $val;
                }
            }
        }
        return ['agent' => $agent, 'sales' => $sales];
    }

    public function getStatus()
    {
        return config('app.seller_status');
    }

    public function changeStatus($id = '')
    {
        $id = intval($id);
        if (empty($id)) {
            return output(-1, '参数错误');
        }
        $status = Db::name('seller')->field('status')->where(['id' => $id])->find();
        if (empty($status)) {
            return output(-1, '商户不存在');
        }
        $status = $status['status'];
        if ($status == 1) {
            $data = ['status' => 2];
        } else {
            $data = ['status' => 1];
        }
        if (Db::name('seller')->where(['id' => $id])->update($data)) {
            return output(0, '更新状态成功');
        } else {
            return output(-1, '更新状态失败');
        }
    }


}